<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <el-tree
          :data="deptDatas"
          :load="getOrgDatas"
          :props="defaultProps"
          :expand-on-click-node="false"
          lazy
          @node-click="handleNodeClick"
        />
      </el-col>
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入名称或者邮箱搜索"
              style="width: 200px"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <date-range-picker v-model="query.createTime" class="date-item" />
            <el-select
              v-model="query.enabled"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible.sync="crud.status.cu > 0"
          :title="crud.status.title"
          width="570px"
        >
          <el-form
            ref="form"
            :inline="true"
            :model="form"
            :rules="rules"
            size="small"
            label-width="66px"
          >
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" />
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model.number="form.mobile" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="机构" prop="orgId">
              <treeselect
                v-model="form.orgId"
                :options="orgs"
                :load-options="loadOrg"
                :normalizer="normalizer"
                style="width: 178px"
                @select="departmentSelectChange"
                placeholder="选择机构"
              />
            </el-form-item>

            <el-form-item label="部门" prop="deptIds">
              <treeselect
                v-model="form.deptIds"
                :options="depts"
                :load-options="loadDepartment"
                :normalizer="normalizer"
                :multiple="true"
                style="width: 178px"
                placeholder="选择部门"
              />
            </el-form-item>

            <el-form-item label="状态">
              <el-radio-group v-model="form.enabled">
                <el-radio
                  v-for="item in dict.user_status"
                  :key="item.id"
                  :label="item.value"
                  >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-bottom: 0" label="角色" prop="roleIds">
              <el-select
                v-model="roleDatas"
                style="width: 437px"
                multiple
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roles"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button
              :loading="crud.status.cu === 2"
              type="primary"
              @click="crud.submitCU"
              >确认</el-button
            >
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          style="width: 100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column
            :selectable="checkboxT"
            type="selection"
            width="55"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            prop="userName"
            label="用户名"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            prop="realName"
            label="姓名"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            prop="mobile"
            width="100"
            label="电话"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            width="135"
            prop="email"
            label="邮箱"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            prop="orgName"
            label="所在机构"
          >
          </el-table-column>
          <el-table-column
          :show-overflow-tooltip="true"
             width="100"
            prop="deptName"
            label="所在部门"
          >
          </el-table-column>
          <el-table-column
          width="100"
          :show-overflow-tooltip="true"
            prop="roleName"
            label="用户角色"
          >
          </el-table-column>
          <el-table-column label="状态" align="center" prop="enabled">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="createDate"
            width="135"
            label="创建日期"
          />
          <el-table-column
            v-if="checkPer(['admin', 'system:user,edit', 'system:user,del'])"
            label="操作"
            width="115"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
                :disabled-dle="scope.row.id === user.userId"
              />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUser from "@/api/system/user";
import crudDepartment from '@/api/system/department';
import { isvalidPhone } from "@/utils/validate";
import { getOrgTree, findAll } from "@/api/system/org";
import { getAll } from "@/api/system/role";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import DateRangePicker from "@/components/DateRangePicker";
import Treeselect from "@riophae/vue-treeselect";
import { mapGetters } from "vuex";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect";
let userRoles = [];
const defaultForm = {
  id: null,
  userName: null,
  realName: null,
  email: null,
  enabled: "false",
  deptIds: null,
  orgId: null,
  mobile: null,
};
export default {
  name: "User",
  components: {
    Treeselect,
    crudOperation,
    rrOperation,
    udOperation,
    pagination,
    DateRangePicker,
  },
  cruds() {
    return CRUD({
      title: "用户",
      url: "api/sys/users/page",
      sort: "createTime,desc",
      crudMethod: { ...crudUser },
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ["user_status"],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!isvalidPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    return {
      height: document.documentElement.clientHeight - 180 + "px;",
      deptName: "",
      orgs: [],
      depts:[],
      deptDatas: [],
      level: 3,
      roles: [],
      roleDatas: [], // 多选时使用
  
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      permission: {
        add: ["admin", "system:user,create"],
        edit: ["admin", "system:user,edit"],
        del: ["admin", "system:user,del"],
      },
      enabledTypeOptions: [
        { key: "true", display_name: "激活" },
        { key: "false", display_name: "锁定" },
      ],
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        realName: [
          { message: "请输入用户昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        mobile: [{ required: true, trigger: "blur", validator: validPhone }],
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  created() {
    this.crud.msg.add = "新增成功，默认密码：123456";
  },
  mounted: function () {
    const that = this;
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + "px;";
    };
  },
  methods: {
    changeRole(value) {
      userRoles = [];
      value.forEach(function (data, index) {
        const role = { id: data };
        userRoles.push(role);
      });
    },

    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value);
        }
      });
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles();
      if (form.orgId != null) {
        this.getAllOrg(form.orgId);
      } else {
        this.initInputOrgTree();
      }
      this.depts.push({ id: 0, name: '顶级类目', children: null })
      crudDepartment
          .getDepartmentTree(null).then((res) => {
          this.depts = res
        })
      form.enabled = form.enabled.toString();
    },

    departmentSelectChange(raw, instanceId){
      console.log(raw, '当前的对象')
      crudDepartment
          .getDepartmentTree({"orgId":raw.id}).then((res) => {
          this.depts = res
        })
    },

    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.roleDatas = [];
    },
    // 初始化编辑时候的角色
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.roleDatas = [];
      userRoles = [];
      const _this = this;
      const formRoleIds = form.roleIds ? form.roleIds.split(",") : [];
      formRoleIds.forEach(function (roleId, index) {
        _this.roleDatas.push(roleId);
        const rol = { id: roleId };
        userRoles.push(rol);
      });
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.orgId) {
        this.$message({
          message: "部门不能为空",
          type: "warning",
        });
        return false;
      } else if (this.roleDatas.length === 0) {
        this.$message({
          message: "角色不能为空",
          type: "warning",
        });
        return false;
      }
      crud.form.deptIds = crud.form.deptIds.toString();
      crud.form.roleIds = userRoles
        .map((item) => {
          return item.id;
        })
        .join(",");
      return true;
    },
    // 获取左侧部门数据
    getOrgDatas(node, resolve) {
      const sort = "id,desc";
      const params = { sort: sort };
      if (typeof node !== "object") {
        if (node) {
          params["name"] = node;
        }
      } else if (node.level !== 0) {
        params["pid"] = node.data.id;
      }
      setTimeout(() => {
        getOrgTree(params).then((res) => {
          if (resolve) {
            resolve(res);
          } else {
            this.deptDatas = res;
          }
        });
      }, 100);
    },

    initInputOrgTree() {
      getOrgTree().then((res) => {
        this.buildOrg(res);
        this.orgs = res;
      });
    },

    getAllOrg(orgId) {
      findAll(orgId).then((data) => {
        this.buildOrg(data);
        this.orgs = data;
      });
    },
    buildOrg(orgs) {
      orgs.forEach((data) => {
        if (data.children) {
          this.buildOrg(data.children);
        }
        if (data.isParent && !data.children) {
          data.children = null;
        }
      });
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 获取弹窗内部门数据
    loadDepartment({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDepartment
          .getDepartmentTree({ pid: parentNode.id == '0' ? null : parentNode.id })
          .then((res) => {
            parentNode.children = res.map(function (obj) {
              if (!obj.leaf) {
                obj.children = null
              }
              return obj
            })
            setTimeout(() => {
              callback()
            }, 100)
          })
      }
    },
    // 获取弹窗内部门数据
    loadOrg({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getOrgTree({ enabled: true, pid: parentNode.id }).then((res) => {
          parentNode.children = res.map(function (obj) {
            if (obj.isParent) {
              obj.children = null;
            }
            return obj;
          });
          setTimeout(() => {
            callback();
          }, 200);
        });
      }
    },


    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.orgId = null;
      } else {
        this.query.orgId = data.id;
      }
      this.crud.toQuery();
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm(
        '此操作将 "' +
          this.dict.label.user_status[val] +
          '" ' +
          data.username +
          ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          crudUser
            .edit(data)
            .then((res) => {
              this.crud.notify(
                this.dict.label.user_status[val] + "成功",
                CRUD.NOTIFICATION_TYPE.SUCCESS
              );
            })
            .catch(() => {
              data.enabled = !data.enabled;
            });
        })
        .catch(() => {
          data.enabled = !data.enabled;
        });
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll()
        .then((res) => {
          this.roles = res;
        })
        .catch(() => {});
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.userId;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
